var db = require('./index.js');
var co = require('co');

function * adsSeed(){
    console.log('AdsSeed');
    for(var i = 0;i < 3;i ++){
        yield db.models.ads.create({
            imgUrl:'/ads/ad' + (i+1) +'.jpg'
        });
    }
}

function * shopsSeed(){
    console.log('shopsSeed');
    var Areas = yield db.models.Area.findAll({
        where:{
            type:2,
            status:0
        },
        attributes:['id']
    });
    for (var i = 0; i < 3; i++) {
        yield db.models.shops.create({
            mainImg: '/jipai.jpg',
            title: '卞留念鸡排饭',
            phone: '18340861711',
            openTime: '10:00 - 22:00',
            location: '大连理工大学软件学院',
            logistic: '大连理工大学软件学院',
            message: '新用户首单立减5元 （在线支付专享）',
            status: 1,
            AreaId:Areas[i % Areas.length].id
        })
    }
}

function * adminerSeed(){
    console.log('adminerSeed');
    var shopId = yield db.models.shops.findAll({
        where:{
            status:1
        }
    });
    for(var i = 0; i < 40; i ++) {
        yield db.models.Adminer.create({
            name: '用户' + i,
            password: '123456',
            phone: '18840823910',
            nickname: '用户' + i,
            type: i % 3 + 1,
            shopId: shopId[i % shopId.length].id
        })
    }
}

function * userSeed(){
    console.log('userSeed');
    for(var i = 0; i < 40; i ++) {
        yield db.models.User.create({
            name: '用户' + i,
            password: '123456',
            phone: '18840823910',
            nickname: '用户' + i,
            headimage: 'http://www.baidu.com',
            sex: 0,
            unionid: 'unionid',
            openid: 'openid',
            joinTime: Date.now(),
            status: 1
        })
    }
}


//这里坑爹的shopId！！！
function * goodsSeed() {
    console.log('goodsSeed');
    var shops = yield db.models.shops.findAll({
        where: {
            status: 1
        }
    });
    for(var i = 0; i < 40; i ++) {
        var goodsTypes = yield db.models.GoodsType.findAll(
            {
                where: {
                    type: 2,
                    shopId:shops[i % shops.length].id
                    //status: 0
                }
            }
        );
        //这里应该加上一个循环
        yield db.models.Goods.create({
            title: '商品' + i,
            mainImg: '/tmp/1 (1).jpg',
            imgs: '["/tmp/1 (2).jpg", "/tmp/1 (3).jpg"]',
            price: 20 + i,
            oldPrice: 10 + i,
            capacity: 20 + i,
            content: '内容' + i,
            GoodsTypeId: goodsTypes[i % goodsTypes.length].id,
            shopId: shops[i % shops.length].id,
            perStr:  i % 2 ? '每斤' : '每个',
            brief: '简介',
            perNum: (i+1) % 6,
            status: 1
        });
    }
}

function * goodsTypeSeed() {
    console.log('goodsTypeSeed');
    var shops = yield db.models.shops.findAll({
        where:{
            status:1
        }
    });
    for(var i = 0;i < shops.length;i++){
        var ids = [];
        var shopid = shops[i % shops.length].id;
        ids.push(yield db.models.GoodsType.create({
            title: '时令水果',
            type: 1,
            shopId: shopid
        }));
        ids.push(yield db.models.GoodsType.create({
            title: '新鲜蔬菜',
            type: 1,
            shopId: shopid
        }));
        ids.push(yield db.models.GoodsType.create({
            title: '禽蛋肉类',
            type: 1,
            shopId: shopid
        }));
        yield db.models.GoodsType.create({
            title: '禽蛋肉类',
            type: 1,
            shopId: shopid
        });
        yield db.models.GoodsType.create({
            title: '叶菜类',
            type: 2,
            GoodsTypeId: ids[0].id,
            shopId: shopid
        });
        yield db.models.GoodsType.create({
            title: '根茎类',
            type: 2,
            GoodsTypeId: ids[0].id,
            shopId: shopid
        });
        yield db.models.GoodsType.create({
            title: '豆类',
            type: 2,
            GoodsTypeId: ids[0].id,
            shopId: shopid
        });
        yield db.models.GoodsType.create({
            title: '精品类',
            type: 2,
            GoodsTypeId: ids[1].id,
            shopId: shopid
        });
        yield db.models.GoodsType.create({
            title: '热带类',
            type: 2,
            GoodsTypeId: ids[1].id,
            shopId: shopid
        });
        yield db.models.GoodsType.create({
            title: '苹果类',
            type: 2,
            GoodsTypeId: ids[1].id,
            shopId: shopid
        });
    }
}

function * msgSeed(){
    console.log('msgSeed');
    var users = yield db.models.User.findAll({});
    for(var i = 0; i < 160; i ++) {
        yield db.models.Msg.create({
            title: '消息测试' + i,
            link: '#',
            UserId: users[i % users.length].id
        })
    }
}

function * areaSeed() {
    console.log('areaSeed');
    var ids = [];
    for (var i = 0; i < 3; i++) {
        ids.push((yield db.models.Area.create({
            title: '一级区域' + i,
            type: 1
        })).id);
    }
    for (i = 0; i < ids.length; i++) {
        for (var j = 0; j < 10; j++) {
            yield db.models.Area.create({
                title: '二级区域' + j,
                type: 2,
                AreaId: ids[i % ids.length],
                TopAreaId: ids[i % ids.length]
            });
        }
    }
    console.log('areaSeed over');
}

function * addressSeed() {
    console.log('addressSeed');
    var users = yield db.models.User.findAll({});
    var areas = yield db.models.Area.findAll({
        where: {
            type: 2
        }
    });
    var defaults = {};
    for(var i = 0; i < 160; i ++) {
        yield db.models.DeliverAddress.create({
            recieverName: '收货人' + i,
            phone: "1884082391" + i % 10,
            province: '辽宁省',
            city: '大连市',
            area: '开发区',
            address: '大连理工大学软件学院',
            isDefault: defaults[users[i % users.length].id] ? false : true,
            UserId: users[i % users.length].id,
            AreaId: areas[i % areas.length].id
        });
        defaults[users[i % users.length].id] = true;
    }
}

function * containerSeed() {
    console.log('containerSeed');
    var shops = yield db.models.shops.findAll({
        where:{
            status:1
        }
    });
    for(var i = 0;i < 3;i ++){
        var value = JSON.stringify({
            basicFare: 10,
            freeLine: 80
        });
        yield db.models.Container.create({
            key: 'fare',
            value: value,
            shopId: shops[i % shops.length].id
        });
    }
}

//该死的shop和good绑定！
function * shoppingCartSeed() {
    console.log('shoppingCartSeed');
    var users = yield db.models.User.findAll({});
    var shops = yield db.models.shops.findAll({
        where:{
            status:1
        }
    });
    for(var i = 0; i < users.length; i ++) {
        for(var j = 0 ; j < shops.length; j ++) {
            var goods = yield db.models.Goods.findAll({
                where:{
                    shopId:shops[j].id
                }
            });
            for(var k = 0;k < goods.length ;k ++){
                s = yield db.models.ShoppingCart.create({
                    num: i + j + 1,
                    UserId: users[i % users.length].id,
                    GoodId: goods[k % goods.length].id,
                    shopId: shops[j % shops.length].id
                });
            }
        }
    }
}

function * orderSeed() {
    console.log('orderSeed');
    var users = yield db.models.User.findAll({});
    var shops = yield db.models.shops.findAll({
        where:{
            status:1
        }
    });
    var areas = yield db.models.Area.findAll({
        where: {
            type: 2
        }
    });
    for(var l = 0;l < shops.length ;l ++){
        var fare = yield db.models.Container.fare(shops[l % shops.length].id);
        var goods = yield db.models.Goods.findAll({
            where:{
                shopId:shops[l % shops.length].id
            }
        });

        for(var i = 0; i < users.length - 20; i ++) {
            for(var j = 0 ; j < 5; j ++) {
                var items = [];
                var price = 0;
                for(var k = 0 ; k < (i + j % 10) + 1; k ++ ){
                    var goodsItem = goods[(i+j+k) % goods.length];
                    price += (i+j+k) * goodsItem.price;
                    items.push(db.models.OrderItem.build({
                        goods: JSON.stringify(goodsItem),
                        price: ((i + j % 10) + 1) * goodsItem.price,
                        num: (i + j % 10) + 1,
                        GoodId: goodsItem.id
                    }));
                }
                var orderFare = 0;
                if (price < parseFloat(fare.freeLine)) {
                    orderFare = fare.basicFare;
                    price += orderFare;
                }
                var order = yield db.models.Order.create({
                    recieverName: '收货人' + i,
                    phone: "1884082391" + i % 10,
                    province: '辽宁省',
                    city: '大连市',
                    area: '开发区',
                    address: '大连理工大学软件学院',
                    price,
                    num: items.length,
                    status: 1,
                    fare: orderFare,
                    message: '留言啊',
                    UserId: users[i].id,
                    AreaId: areas[i % areas.length].id,
                    shopId: shops[l % shops.length].id
                });
                for(var k = 0 ; k < items.length; k ++ ){
                    items[k].OrderId = order.id;
                    yield items[k].save();
                }
            }
        }
    }

}

function * init() {
    console.log('init');
    yield db.sync({force: true});
    yield adsSeed();
    yield areaSeed();
    yield shopsSeed();
    yield adminerSeed();
    yield addSuperAdminer();
    yield goodsTypeSeed();
    yield userSeed();
    yield goodsSeed();
    yield msgSeed();
    yield addressSeed();
    yield containerSeed();
    yield shoppingCartSeed();
    yield orderSeed();
}

function *addSuperAdminer() {
    console.log('addSuperAdminer');
    yield db.models.Adminer.create({
        nickname: 'super',
        name: '超级管理员',
        phone: '12345678901',
        password: '123456',
        status: 0,
        type: 100
    });
}

function *production() {
    console.log('production state');
    yield db.sync({force: true});
    yield addSuperAdminer();
    //require('../scripts/goodstype-seed');
    //require('../scripts/goods-seed');
}

var pro = process.argv[2] == '--pro';
co(function * () {
    if(pro){
        yield production();
    }else{
        yield init();
    }
    //yield db.models.Area.destroy({where:{},individualHooks: true}) ;
    //yield areaSeed();
    console.log('finished ...');
    process.exit(0);
}).catch(function (err){
    console.log(err.stack);
});







